﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Afvanding.RefToPumpService;

namespace Afvanding
{
    public class WaterMonitor
    {
        private int _stationId;
        public double Level { get; private set; }
        private object _locker;
        private DateTime _date;
        public bool IsRunning;
        //private int _count;
        //public event WaterLevel LevelValue;
        public event RainValue RainValue;
        public event DrainValue DrainValue;

        public WaterMonitor(int stationId, DateTime date)
        {
            _stationId = stationId;
            //_count = 0;
            _date = date;
            Level = 0;
            _locker = new object();
            IsRunning = true;
        }

        public void Enqueue(double value)
        {
            lock (_locker)
            {
                while (!IsRunning)
                    Monitor.Wait(_locker);
                _date = _date.AddMinutes(1);
                Level += value;
                RainValue(_stationId, _date, value, Level);
                //LevelValue(_stationId, _date.AddMinutes(_count), Level);
                //LevelValue(_stationId, _date, Level);
                Monitor.Pulse(_locker);
            }
        }

        public void Dequeue(int pumpId, double value)
        {
            lock (_locker)
            {
                while (Level <= 0 && !IsRunning)
                    Monitor.Wait(_locker);
                value = Level > 0 && Level >= value ? value : Level; //if there's water, find how much to drain, o
                Level = Level > 0 && Level >= value ? Level - value : 0; //new level dependant on drain, o
                DrainValue(_stationId, pumpId, _date, value, Level);
                //LevelValue(_stationId, _date.AddHours(_count), Level);
                //LevelValue(_stationId, _date, Level);
            }   
        }
    }
}
